package com.topit.show.wxapi.common;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;
import com.topit.show.core.util.RequestHandler;
import com.topit.show.core.util.Sha1Util;
import com.topit.show.core.util.SignUtil;
import com.topit.show.core.util.StrUtil;
import com.topit.show.core.util.XmlUtil;

public class WxPayUtil {

	public static String getPrePayId(String openId, String body, int type, String orderId, int money, String ip,String attach) {
		// 参数Map
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", WxConstants.APPID);
		params.put("mch_id", WxConstants.MCHID);
		params.put("nonce_str", StrUtil.getRandomString(32));
		params.put("body", body);
		params.put("attach", attach);
		params.put("out_trade_no", orderId);
		params.put("total_fee", String.valueOf(money));
		params.put("spbill_create_ip", ip);
		params.put("notify_url", WxConstants.NOTIFY_URL);
		params.put("trade_type", "JSAPI");
		params.put("openid", openId);
		// 生成签名
		String sign = SignUtil.getSign(params);
		params.put("sign", sign);
		// 生成参数xml串
		String xml = XmlUtil.getXmlParams(params);
		// 微信下单
		String prepay_id = null;
		String url = WeixinApiUrl.unified_order;
		String response;
		try {
			response = WeixinApiUtil.httpRequest(WxConstants.APPID, url, "POST", xml);
			if (response.contains("prepay_id")) {
				prepay_id = response.substring(response.indexOf("<prepay_id>") + 20, response.indexOf("</prepay_id>") - 3);
			}
		} catch (Exception e) {
		}
		return prepay_id;
	}

	public static String getPayJson(String prepay_id,String nonce_str) {
		 nonce_str = "呼呼订单";
		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		String timestamp = Sha1Util.getTimeStamp();
		finalpackage.put("appId", WxConstants.APPID);
		finalpackage.put("timeStamp", timestamp);
		finalpackage.put("nonceStr", nonce_str);
		finalpackage.put("signType", "MD5");
		finalpackage.put("package", "prepay_id=" + prepay_id);
		RequestHandler reqHandler = new RequestHandler(null, null);
		reqHandler.init(WxConstants.APPID, null, WxConstants.APIKEY);
		String finalsign = reqHandler.createSign(finalpackage);
		JSONObject retMsgJson = new JSONObject();
		retMsgJson.put("appId", WxConstants.APPID);
		retMsgJson.put("timeStamp", timestamp);
		retMsgJson.put("nonceStr", nonce_str);
		retMsgJson.put("package", "prepay_id=" + prepay_id);
		retMsgJson.put("signType", "MD5");
		retMsgJson.put("paySign", finalsign);
		return retMsgJson.toString();
	}
}
